package com.acmen.easyapi.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author acmen
 * 请求工具
 */
public class RequestUtil {
    public static ThreadLocal<HttpServletRequest> currentRequest = new ThreadLocal();


    /**
     * IP在头部传递可能key列表
     */
    private final static String[] HEADER_IP_KEYS = {"X-Real-IP","x-forwarded-for","WL-Proxy-Client-IP","HTTP_CLIENT_IP","HTTP_X_FORWARDED_FOR"};

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = null;
        try {
            request = getRequestAttributes().getRequest();
        } catch (Exception e) {

        }
        if(request == null){
            request = currentRequest.get();
        }
        return request;
    }

    public static String getIpAddress() {
        return getIpAddress(getRequest());
    }

    /**
     * 根据requesth获取用户真实ip.
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;
        for(String key : HEADER_IP_KEYS){
            ip = request.getHeader(key);
            if(StringUtil.isNotEmpty(ip)){
                break;
            }
        }
        if(StringUtil.isEmpty(ip)){
            ip = request.getRemoteAddr();
        }
        if (StringUtil.isNotEmpty(ip) && ip.contains(",")) {
            List<String> ips = Arrays.asList(ip.split(",")).stream().distinct().collect(Collectors.toList());
            ip = StringUtils.join(ips, ",");
        }
        return ip;
    }

    public static ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes) attributes;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        try {
            return getRequestAttributes().getResponse();
        } catch (Exception e) {
            return null;
        }
    }


    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
        return map;
    }
}
